import styled from "@emotion/styled";
import { Drawer, Form, Spin, Input, Button } from "antd";
import { DrawerProps } from "antd/es/drawer";
import { useForm } from "antd/lib/form/Form";
import { ErrorBox } from "components/lib";
import { useEffect } from "react";
import { useAddSearch, useModifySearch, useEditSearch } from "./utils";

export const CreateSearch = (
  props: Pick<DrawerProps, "visible"> & { onClose: () => void }
) => {
  const {
    mutateAsync: addSearch,
    isLoading: isloading,
    error,
  } = useAddSearch();

  const { mutateAsync: modifySearch, isLoading: isModifyLoading } =
    useEditSearch();

  const [form] = useForm();

  const onFinish = async (values: any) => {
    if (hot) {
      await modifySearch({ ...form.getFieldsValue(), id })
        .then(() => {
          props.onClose();
        })
        .catch((error) => error);
    } else {
      await addSearch({ ...form.getFieldsValue() })
        .then(() => {
          props.onClose();
        })
        .catch((error) => error);
    }
  };

  const { hot, isLoading, id } = useModifySearch();

  useEffect(() => {
    if (hot) {
      form.setFieldsValue(hot);
      // console.log(hot);
    } else {
      form.resetFields();
    }
  }, [form, props.visible, hot]);

  return (
    <Drawer
      visible={props.visible}
      onClose={props.onClose}
      forceRender={true}
      destroyOnClose={true}
      width={"100%"}
    >
      <Container>
        {isloading || isLoading ? (
          <Spin size={"large"} />
        ) : (
          <>
            <h2>{hot ? "编辑" + hot.name : "创建热门搜索"}</h2>
            <ErrorBox error={error} />
            <Form
              form={form}
              layout={"vertical"}
              style={{ width: "40rem" }}
              onFinish={onFinish}
            >
              <Form.Item
                label={"名称"}
                name={"name"}
                rules={[{ required: true, message: "请输入名称 " }]}
              >
                <Input placeholder="请输入名称" />
              </Form.Item>
              <Form.Item style={{ textAlign: "right" }}>
                <Button
                  loading={isloading || isModifyLoading}
                  type={"primary"}
                  htmlType={"submit"}
                >
                  提交
                </Button>
              </Form.Item>
            </Form>
          </>
        )}
      </Container>
    </Drawer>
  );
};

const Container = styled.div`
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
`;
